package com.shopx.core.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
 * @author hyh
 * @version 创建时间：2016年3月8日 上午11:12:30 类说明
 */
public class ReflectUtils {

  public static Field[] getAllField(Class<?> clazz) {
    ArrayList<Field> fieldList = new ArrayList<Field>();
    Field[] dFields = clazz.getDeclaredFields();
    if (null != dFields && dFields.length > 0) {
      fieldList.addAll(Arrays.asList(dFields));
    }

    Class<?> superClass = clazz.getSuperclass();
    if (superClass != Object.class) {
      Field[] superFields = getAllField(superClass);
      if (null != superFields && superFields.length > 0) {
        for (Field field : superFields) {
          if (!isContain(fieldList, field)) {
            fieldList.add(field);
          }
        }
      }
    }
    Field[] result = new Field[fieldList.size()];
    fieldList.toArray(result);
    return result;
  }

  private static boolean isContain(ArrayList<Field> fieldList, Field field) {
    for (Field temp : fieldList) {
      if (temp.getName().equals(field.getName())) {
        return true;
      }
    }
    return false;
  }

  public static Object getFieldValueByName(String fieldName, Object obj) throws Exception {
    //判断Obj是否为Map
    if (obj instanceof Map) {
      return ((Map) obj).get(fieldName);
    } else {
      String firstLetter = fieldName.substring(0, 1).toUpperCase();
      String getter = "get" + firstLetter + fieldName.substring(1);
      Method method = obj.getClass().getMethod(getter, new Class[]{});
      Object value = method.invoke(obj, new Object[]{});
      if (value == null) {
        return "";
      }
      return value;
    }

  }
}
